<?php
/**
 * 文件上传
 */

namespace app\admin\controller\admin;


use app\common\controller\Backstage;
use app\common\model\FileRecord;
use thans\jwt\facade\JWTAuth;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("上传文件相关")
 */
class Upload extends Backstage
{

    //中间件不验证的方法
    protected $middleware = [
        'app\\middleware\\Admin' => [
            'except' => []
        ]
    ];

    /**
     * @Apidoc\Title("图片上传")
     * @Apidoc\Url("/admin/admin.Upload/uploadImg")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("file", require=true, desc="上传名字")
     * @Apidoc\Returned("data", type="string", desc="文件上传信息")
     */
    public function uploadImg()
    {
        $file = request()->file('file');
        if (empty($file)) {
            return $this->ajax(0, "上传为空");
        }
        try {
            // 验证
            validate(['file' => [
                'fileSize' => 10485760,//30M
                'fileExt' => 'jpg,jpeg,png,bmp,gif'
                // 'fileMime' => 'image/jpeg,image/png,image/gif', //这个一定要加上，很重要我认为！
            ]])->check(['file' => $file]);
            $info = $this->preservation($file);
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '成功', $info);
    }


    /**
     * @Apidoc\Title("视频上传")
     * @Apidoc\Url("/admin/admin.Upload/uploadVideo")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("file", require=true, desc="上传名字")
     * @Apidoc\Returned("data", type="string", desc="文件上传信息")
     */
    public function uploadVideo()
    {
        $file = request()->file('file');

        if (empty($file)) {
            return $this->ajax(0, "上传为空");
        }
        try {
            // 验证
            validate(['file' => [
                'fileSize' => 1073741824,//1024M
                'fileExt' => 'mp4,AVI,WMV'
            ]])->check(['file' => $file]);
            $info = $this->preservation($file);

        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '成功', $info);
    }

    /**
     * @Apidoc\Title("文件上传")
     * @Apidoc\Url("/admin/admin.Upload/uploadFile")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("file", require=true, desc="上传名字")
     * @Apidoc\Returned("data", type="string", desc="文件上传信息")
     */
    public function uploadFile()
    {
        $file = request()->file('file');
        if (empty($file)) {
            return $this->ajax(0, "上传为空,name=file");
        }
        try {
            // 验证
            validate(['file' => [
                'fileSize' => 1073741824,//1G
                'fileExt' => 'pptx,xlsx,txt,pdf'
            ]])->check(['file' => $file]);
            $info = $this->preservation($file);
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '成功', $info);
    }

    /**
     * 保存到服务器
     * @param $file 上传文件
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function preservation($file)
    {
        //获取登录人信息
        $payload = JWTAuth::auth();
        $admin['id'] = $payload['admin_id'];
        $route = $this->request->domain();
        $info = new FileRecord();
        $file_record = $info
            ->where([
                'admin_id' => $admin['id'],
                'sha1' => $file->hash(),
                'md5' => $file->md5(),
                'file_name' => $_FILES['file']['name'],
            ])
            ->find();
        //服务器没有
        if (empty($file_record)) {
            // 上传图片到本地服务器
            $saveName = \think\facade\Filesystem::disk('public')
                ->putFile('upload', $file);
            $src = "/{$saveName}";
            $url = $route . $src;
            $info->save([
                'http_url' => $url,
                'src' => $src,
                'admin_id' => $admin['id'],
                'sha1' => $file->hash(),
                'md5' => $file->md5(),
                'file_size' => $_FILES['file']['size'],
                'file_name' => $_FILES['file']['name'],
                'file_mime' => $_FILES['file']['type'],
            ]);
        } else {
            $src = $file_record->src;
            $url = get_file_url($src);
        }
        return [
            'src' => $src,
            'url' => $url,
            'sha1' => $file->hash(),
            'md5' => $file->md5(),
            'file_size' => $_FILES['file']['size'],
            'file_name' => $_FILES['file']['name'],
            'name' => $_FILES['file']['name'],
        ];
    }
}
